package com.example.demo.common.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 树形结构
 */
public class TreeNode {

    private String id;

    private String pid;

    private String name;

    private String title;

    private Integer type;

    private List<TreeNode> children;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPid() {
        return pid;
    }

    public void setPid(String pid) {
        this.pid = pid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }

    public List<TreeNode> getChildren() {
        return children;
    }

    public void setChildren(List<TreeNode> children) {
        this.children = children;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public TreeNode(String id, String pid, String name, Integer type) {
        this.id = id;
        this.pid = pid;
        this.name = name;
        this.type = type;
        this.children = new ArrayList<TreeNode>();
    }

    public TreeNode(String id, String pid, String name ) {
        this.id = id;
        this.pid = pid;
        this.name = name;
        this.children = new ArrayList<TreeNode>();
    }

    public static List<TreeNode> listToTree(List<TreeNode> list) {
        //用递归找子
        TreeNode node = list.get(0);
        String pid = node.getPid();
        List<TreeNode> treeList = new ArrayList<TreeNode>();
        for (TreeNode tree : list) {
            if (tree.getPid().equals(pid)) {
                treeList.add(findChildren(tree, list));
            }
        }
        return treeList;
    }

    private static TreeNode findChildren(TreeNode tree, List<TreeNode> list) {
        for (TreeNode node : list) {
            if (node.getPid().equals(tree.getId())) {
                if (tree.getChildren() == null) {
                    tree.setChildren(new ArrayList<TreeNode>());
                }
                tree.getChildren().add(findChildren(node, list));
            }
        }
        return tree;
    }
}
